from fastapi import APIRouter, UploadFile, File, HTTPException, Depends
from fastapi.responses import FileResponse
import os
from datetime import datetime
from typing import List

from app.services.ifc_service import process_ifc_file, save_json_result
from app.utils.file_utils import save_uploaded_file
from app.dependencies import validate_file_type, validate_file_size
from app.models.ifc_models import IFCConversionResponse, ErrorResponse

router = APIRouter()

@router.post(
    "/convert-ifc",
    response_model=IFCConversionResponse,
    responses={400: {"model": ErrorResponse}, 500: {"model": ErrorResponse}}
)
async def convert_ifc_to_json(
        file: UploadFile = Depends(validate_file_type),
        file_validated: UploadFile = Depends(validate_file_size)
):
    """
    上传IFC文件并将其转换为JSON格式

    - **file**: IFC格式的文件
    """
    try:
        # 保存上传的文件
        file_path = save_uploaded_file(file)

        # 处理IFC文件
        result = process_ifc_file(file_path)

        # 保存JSON结果
        json_file_path = save_json_result(result, file.filename)

        return {
            "status": "success",
            "message": "IFC文件成功转换为JSON",
            "data": result,
            "file_name": os.path.basename(json_file_path),
            "conversion_time": datetime.now()
        }

    except Exception as e:
        raise HTTPException(
            status_code=500,
            detail=f"转换失败: {str(e)}"
        )

@router.get("/files")
async def list_converted_files():
    """获取所有已转换的文件列表"""
    try:
        files = []
        for file in os.listdir("data/output"):
            if file.endswith(".json"):
                file_path = os.path.join("data/output", file)
                file_size = os.path.getsize(file_path)
                files.append({
                    "name": file,
                    "size": f"{file_size / 1024:.2f} KB",
                    "path": file_path
                })

        return {"files": files}
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取文件列表失败: {str(e)}")

@router.get("/download/{filename}")
async def download_json_file(filename: str):
    """下载生成的JSON文件"""
    file_path = os.path.join("data/output", filename)

    if not os.path.exists(file_path) or not filename.endswith(".json"):
        raise HTTPException(status_code=404, detail="文件未找到")

    return FileResponse(
        file_path,
        media_type="application/json",
        filename=filename
    )